package com.zhangxin.wbsocket;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.time.LocalDateTime;
import java.util.Locale;

public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private static ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {

        String content = textWebSocketFrame.text();
        System.out.println("[客户端发过来的消息]:" + content);

        for (Channel channel : group) {
            channel.writeAndFlush(new TextWebSocketFrame("[服务器在]" + LocalDateTime.now()
                    + "[接受到一个消息]" + content));
        }
    }

    /**
     * 将每次建立的连接，放到group中， 后面群发消息的时候使用
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        group.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("[客户端断开，channle对应的长id为：:" +ctx.channel().id().asLongText());
        System.out.println("[客户端断开，channle对应的短id为：]:" +ctx.channel().id().asShortText());
    }
}
